<script>
/*
 * @Author: Your name
 * @Date:   2020-08-10 15:53:24
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-08-11 21:09:31
 */
</script>
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <!-- 分类按钮 -->
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        class="treetable"
        :data="categoryList"
        :columns="columns"
        show-index
        index-text="#"
        :selection-type="false"
        :expand-type="false"
        border
        :show-row-hover="true"
      >
        <!-- 是否有效的列 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-success" v-else style="color: lightgreen"></i>
        </template>
        <!-- 分类等级 -->
        <template slot="order" slot-scope="scope">
          <el-tag :disable-transitions="false" v-if="scope.row.cat_level === 0"
            >一级分类</el-tag
          >
          <el-tag v-else-if="scope.row.cat_level === 1" type="success"
            >二级分类</el-tag
          >
          <el-tag v-else type="warning">三级分类</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="showEditCateDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="deleteCate(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 编辑分类弹出框 -->
    <el-dialog title="编辑分类" :visible.sync="dialogEditCateVisible">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="分类名称" prop="cateName">
          <el-input v-model="editForm.cateName" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="doEditCate">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加分类弹出框 -->
    <el-dialog title="添加分类" :visible.sync="dialogAddCateVisible" @click="closeAddCateDialog">
      <el-form
        :model="addForm"
        ref="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options 用来指定数据源 -->
          <!-- props 用来指定配置对象 -->
          <el-cascader
            expand-trigger="hover"
            :options="parentsCateList"
            :props="cascaderProp"
            v-model="selectedKeys"
            @change="cascaderHandleChange"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddCateVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAddCate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { request2 } from 'network/request.js'
export default {
  name: 'Cate',
  data() {
    return {
      // 分类数据
      categoryList: [],
      // 表格每列的配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok'
        },
        {
          label: '分类等级',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      // 分页查询的数据
      queryinfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 数据总个数
      total: 0,
      // 编辑分类页面的显示
      dialogEditCateVisible: false,
      // 编辑分类表单
      editForm: {
        cateName: '',
        cateId: null
      },
      // 编辑分类表单校验非空
      editRules: {
        cateName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 添加分类页面的显示
      dialogAddCateVisible: false,
      // 添加分类表单
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      // 添加分类校验
      addRules: {
        cateName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 级联选择器中的数据
      parentsCateList: [],
      // 配置级联选择器
      cascaderProp: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框中选择的数组
      selectedKeys: []
    }
  },
  created() {
    this.getCateData()
  },
  methods: {
    // 获取商品分类数据
    async getCateData() {
      let res = await request2({
        url: '/categories',
        method: 'get',
        params: this.queryinfo
      })
      if (res.meta.status !== 200) {
        this.$message.error('商品分类数据获取失败')
      }
      console.log(res)
      this.categoryList = res.data.result
      this.total = res.data.total
    },
    // 分页改变页面大小
    handleSizeChange(val) {
      this.queryinfo.pagesize = val
      this.getCateData()
    },
    // 分页改变当前页数
    handleCurrentChange(val) {
      this.queryinfo.pagenum = val
      this.getCateData()
    },
    // 显示编辑分类弹出框
    showEditCateDialog(cateinfo) {
      console.log(cateinfo)
      this.editForm.cateName = cateinfo.cat_name
      this.editForm.cateId = cateinfo.cat_id
      this.dialogEditCateVisible = true
    },
    // 确认提交编辑信息按钮
    doEditCate() {
      this.$refs.editForm.validate(async valid => {
        if (!valid) {
          return
        }
        let res = await request2({
          url: `/categories/${this.editForm.cateId}`,
          method: 'put',
          data: {
            cat_name: this.editForm.cateName
          }
        })
        if (res.meta.status !== 200) {
          this.$message.error('分类信息编辑失败')
        }
        this.$message.success('分类信息编辑成功')
        this.dialogEditCateVisible = false
        this.getCateData()
      })
    },
    // 删除分类
    deleteCate(userinfo) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          request2({
            url: `/categories/${userinfo.cat_id}`,
            method: 'delete'
          }).then(res => {
            if (res.meta.status !== 200) {
              this.$message.error('删除失败')
            }
            this.$message.success('删除分类成功')
            this.getCateData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 显示添加分类弹出框
    showAddCateDialog() {
      this.getParentsCateList()
      this.dialogAddCateVisible = true
    },
    // 关闭添加分类弹出框
    closeAddCateDialog() {
      /*
        清空表单数据，将selectedkeys数组清空,
        否则就算级联框中数字清空了，实际selectedkeys数组还继续存在
      */
      this.$refs.addForm.resetFields()
      this.selectedKeys = []
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
    },
    // 确认提交添加分类
    doAddCate() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        let res = await request2({
          url: '/categories',
          method: 'post',
          data: this.addForm
        })
        if(res.meta.status !== 201) {
          this.$message.error('提交分类数据失败')
          return
        }
        this.$message.success('提交分类数据成功')
        this.getCateData()
        this.dialogAddCateVisible = false
      })
    },
    // 获得父级分类信息
    async getParentsCateList() {
      let res = await request2({
        url: '/categories',
        method: 'get',
        params: {
          type: 2
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取父级分类信息失败')
      }
      this.parentsCateList = res.data
    },
    // 监听级联选择框改变的事件
    cascaderHandleChange() {
      /*
        监听级联框的改变，选中的分类结果返回的是一个数组
        如果数组的长度不大于0，说明没有选择任何分类，是顶级的分类
        如果数据的长度大于0，说明选择的是二级分类或者是三级分类
        通过数组的长度发现规律给pid和level进行赋值
      */
      console.log(this.selectedKeys)
      if(this.selectedKeys.length > 0) {
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addForm.cat_level = this.selectedKeys.length
        console.log("addform对象",this.addForm)
        return
      }else{
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    }
  }
}
</script>
<style lang="less">
.el-card {
  margin-top: 20px;
  .treetable {
    font-size: 14px;
    margin-top: 20px;
    margin-bottom: 20px;
  }
}
.el-cascader {
  width: 100%;
}
</style>
